import { Col, Empty, Spin, Tabs } from 'antd';
import { ContractHomeContext } from '../../../common';
import _ from 'lodash';
import Cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';
import ReactDOM from 'react-dom';
import * as echarts from 'echarts';
import React, { useContext, useEffect, useMemo, useRef } from 'react';
import { ContractHomePageCountAPI } from '../../../common/type';
import { float_add } from '../mconfig';

export const ContractCountPaymentRight: React.FC<ContractHomePageCountAPI.IContractCountCollecRight> = ({ countLoading }) => {
  /**引入上下文 */
  const { styleFixCls, copeWithData, curRes } = useContext(ContractHomeContext);
  /** 折线图Ref */
  let pieChartRef: any = useRef();
  useEffect(() => {
    renderPieChart(copeWithData);
  }, [copeWithData]);

  const renderMemo = useMemo(() => {
    let sum: number | string = 0;
    let paid = 0;
    let residue = 0;

    copeWithData?.forEach((item) => {
      sum = float_add(sum, item?.totalSum ? item?.totalSum : 0);
      // sum += Number(item?.totalSum) || 0;
      paid += Number(item?.totalPaid) || 0;
      residue += Number(item?.totalResidue) || 0;
    });
    return {
      sum,
      paid,
      residue,
    };
  }, [copeWithData]);

  const calculatePercentage = (A, B) => {
    // 避免除以零的情况
    if (A === 0) {
      return 0;
    }

    // 计算百分比
    const percentage = (B / A) * 100;

    // 保留两位小数
    return parseFloat(percentage.toFixed(2));
  };

  const renderPieChart = (data) => {
    if (pieChartRef?.current) {
      const putStateViewDiv: any = ReactDOM.findDOMNode(pieChartRef?.current);
      const myChart = echarts.init(putStateViewDiv);
      let option = {
        title: {
          text: `应付总额：${renderMemo?.sum} 元`,
          left: 'left',
        },
        tooltip: {
          trigger: 'item',
        },
        legend: {
          left: 0,
          top: '40%',
          orient: 'vertical',
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '55%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center',
            },
            emphasis: {
              label: {
                show: false,
                fontSize: 40,
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              { value: renderMemo?.paid, name: '实付金额' },
              { value: renderMemo?.residue, name: '未付金额' },
            ],
            itemStyle: {
              color: function (colors) {
                var colorList = ['#fc8251', '#ccc'];
                return colorList[colors.dataIndex];
              },
            },
          },
        ],
        graphic: [
          {
            type: 'text', // 类型，可以是文字、图片或其它类型
            id: 'text1',
            left: 'center',
            top: '40%',
            style: {
              text: `应付率`,
              fill: '#919399', // 文字的颜色
              fontSize: 18,
            },
          },
          {
            type: 'text', // 类型，可以是文字、图片或其它类型
            id: 'text2',
            left: 'center',
            top: '50%',
            style: {
              text: `${calculatePercentage(renderMemo?.sum, renderMemo?.paid)}%`,
              fill: '#000000', // 文字的颜色
              fontSize: 25,
            },
          },
        ],
      };
      myChart.setOption(option as any);
    }
  };

  /** tab配置 */
  const tabsItem = useMemo(() => {
    return [
      {
        label: '应付账款',
        key: '1',
        children: copeWithData?.length ? (
          <div className={`${styleFixCls}RootDiv-echartBoxDiv`} ref={pieChartRef}></div>
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ),
      },
    ];
  }, [curRes, copeWithData?.length]);
  return (
    <Col span={8}>
      <Spin spinning={countLoading}>
        <div className={Cls(pageStyles['commonTabsLine'])} style={{ height: '100%', width: '100%' }}>
          <Tabs items={tabsItem} />
        </div>
      </Spin>
    </Col>
  );
};
